//
//  CALoginViewController.m
//  CleanerAir_Project
//
//  Created by 付亚杰 on 16/6/2.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "CALoginViewController.h"
#import "CAPersonalBusinessViewController.h"
#import "CAPersonalRegisteredVC.h"
#import "NSString+Check.h"
#import "CALoginModel.h"
#import "NSString+MD5.h"
#import "SHLoginCMSModle.h"
#import "UMSocialSnsPlatformManager.h"
//#import "UMSocialAccountEntity.h"
#import "UMSocialAccountManager.h"

@interface CALoginViewController ()<UITextFieldDelegate>

//用户名
@property (weak, nonatomic) IBOutlet UIImageView *nameImageView;

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

//密码
@property (weak, nonatomic) IBOutlet UIImageView *pwdImageView;

@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;

@property (weak, nonatomic) IBOutlet UIImageView *clearePwdImageView;

//三方登录
@property (weak, nonatomic) IBOutlet UIImageView *QQLoginImageView;

@property (weak, nonatomic) IBOutlet UIImageView *wechatLoginImageView;

@property (weak, nonatomic) IBOutlet UIImageView *sinaLoginImageView;

@end

@implementation CALoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.nameTextField.delegate = self;
    self.pwdTextField.delegate = self;
    
    //清楚文本天加手势
    [self.clearePwdImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clearePwd)]];
    
    //三方登录添加手势
    [self.QQLoginImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(QQLogin)]];
    
    [self.wechatLoginImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(wechatLogin)]];
    
    [self.sinaLoginImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sinaLogin)]];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNotice:) name:@"tongzhiLogin" object:nil];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 注册
- (IBAction)registeredClick:(id)sender {
    
    CAPersonalBusinessViewController *registered = [[CAPersonalBusinessViewController alloc] init];
 
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:registered animated:YES];
    
}

#pragma mark -- 忘记密码
- (IBAction)forgetPassword:(id)sender {
    
    CAPersonalRegisteredVC *forgetPwd = [[CAPersonalRegisteredVC alloc] init];
    
    forgetPwd.verificationCodeType = FORGET_PASSWORD;//设置验证码页面为忘记密码
    
    forgetPwd.registeredVCBlock = ^{
        
        [self.navigationController popViewControllerAnimated:YES];
    };
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:forgetPwd animated:YES];
    
}

#pragma mark -- TextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if(textField.tag == 10){
        self.nameImageView.image = [UIImage imageNamed:@"用户名蓝.png"];
    }else{
        self.pwdImageView.image = [UIImage imageNamed:@"密码蓝.png"];
        self.clearePwdImageView.hidden = NO;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField.tag == 10) {
        self.nameImageView.image = [UIImage imageNamed:@"用户名"];
    }else{
        self.pwdImageView.image = [UIImage imageNamed:@"密码"];
    }
    self.clearePwdImageView.hidden = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark -- 清楚密码
- (void)clearePwd{
    
    self.pwdTextField.text = @"";
}

#pragma mark -- 登录按钮
- (IBAction)login:(id)sender {
    
    NSString *name = self.nameTextField.text;
    NSString *pwd = self.pwdTextField.text;
    
    
    if ([name isEqualToString:@""]) {
        [ShowMessage showCenterViewMessage:@"请填写用户名"];
    }else if ([pwd isEqualToString:@""]){
        [ShowMessage showCenterViewMessage:@"请填写密码"];
    }else{
        
        if ([NSString isPwd:pwd]) {
            [ShowMessage showCenterViewMessage:@"密码只能是数字或者字母"];
        }else{
            
            [self showIndicator:@"正在登录，请稍候..."];
            [self loginWithRequestToServer:name pwd:pwd];
            
        }
        
    }
    
}

#pragma mark -- 三方登录
- (void)QQLogin{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        //        DLog(@"结果：%u",response.responseCode);
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
            if (_loginBlock != nil) {
                _loginBlock(snsAccount.usid,@"2");
            }
            
            
        }});
    
}

- (void)wechatLogin{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            NSDictionary *dict = [UMSocialAccountManager socialAccountDictionary];
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToWechatSession];
            
            //            NSLog(@"\nusername = %@,\n usid = %@,\n token = %@ iconUrl = %@,\n unionId = %@,\n thirdPlatformUserProfile = %@,\n thirdPlatformResponse = %@ \n, message = %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL, snsAccount.unionId, response.thirdPlatformUserProfile, response.thirdPlatformResponse, response.message);
            //
            NSLog(@"\nusername = %@,\n usid = %@,\n token = %@ iconUrl = %@,\n unionId = %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL, snsAccount.unionId);
            
            if (_loginBlock != nil) {
                _loginBlock(snsAccount.usid,@"4");
            }
            
        }
        
    });
}

- (void)sinaLogin{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
            if (_loginBlock != nil) {
                _loginBlock(snsAccount.usid,@"3");
            }
            
        }});
}

#pragma mark -- 登录请求服务器 && 登录妙恋 服务器
- (void)loginWithRequestToServer:(NSString *)name pwd:(NSString *)pwd{
    
    __typeof(self) weakSelf = self;
    [HTTPManager post:GET_URLString(@"Api/Member/login") parameters:@{@"phone":name,@"password":pwd} success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            [ShowMessage showCenterViewMessage:@"登录成功"];
            
            //保存本地
            [[LoginSingleton sharedLoginSingleton] loginSuccess:responseObject];
            
//            if (weakSelf.loginBlock != nil) {
//                weakSelf.loginBlock();
//            }
            
            //登录妙恋
            [weakSelf loginMiotLinkWebServiceWithUserName:name password:pwd];
            
        }else{
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        [weakSelf hideIndicator];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf hideIndicator];

    }];
}

- (void)loginMiotLinkWebServiceWithUserName:(NSString *)userName
                                   password:(NSString *)password{
    
    [[SHLoginCMSModle shareInstence]connectCMSgetName:userName getPaw:[password MD5] sendBlcok:^(id obj) {
        
        NSLog(@"%@",obj);
    }];
    
}


#pragma mark -- 妙恋登录回调通知
-(void)loginNotice:(NSNotification *)text
{
    
        [LoginSingleton sharedLoginSingleton].cuid = text.userInfo[@"cuid"];
    NSLog(@"%@",[LoginSingleton sharedLoginSingleton].cuid);
  NSString*  LoginStr = [NSString stringWithFormat:@"%@  cuid为%@",text.userInfo[@"Login"],text.userInfo[@"cuid"]];
    
    
    if ([[[UIDevice currentDevice]systemVersion] floatValue]<8.0)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:LoginStr delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [alert show];
        });
        
        
    }
    else
    {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:LoginStr preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            [[NSUserDefaults standardUserDefaults] setObject:self.nameTextField.text forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults] setObject:[self.pwdTextField.text MD5] forKey:@"password"];
            
            if (self.loginBlock != nil) {
                self.loginBlock(nil,@"1");
            }
        }];
        
        [alert addAction:okAction];
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self presentViewController:alert animated:YES completion:nil];
            
        });
    }

    
//    if (self.loginBlock != nil) {
//        self.loginBlock();
//    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
